# coding=utf-8
import codecs
import json

import datetime

import os

from core.m_logging import logger


class JsonFileOutput(object):
    def __init__(self, base_path):
        self.base_path = base_path

    def output(self, content):
        batch_no = content["batch_no"]
        task_no = content["task_no"]
        today = datetime.datetime.now().strftime('%Y-%m-%d')
        current_node_path = "%s/%s/%s/%s" % (batch_no, task_no, today, content["node_no"])
        file_name = "amazon_ansi_%s_%s.json" % (content["node_no"], content["page_no"])

        output_path = "%s/%s/%s" % (self.base_path, current_node_path, file_name)

        if not os.path.isdir(os.path.dirname(output_path)):
            os.makedirs(os.path.dirname(output_path))

        with codecs.open(output_path, mode='ab+', encoding='utf-8') as f:
            line = json.dumps(content)
            logger.info('output file to %s...' % output_path)
            f.write(line.decode("unicode_escape"))
